import {createRouter, createWebHistory } from "vue-router";
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import store from '@/store'
import { getToken } from '@/utils/token'
import {ElMessage} from 'element-plus'
NProgress.configure({ showSpinner: false, easing: 'ease', speed: 500 })
const whiteList = ['/login', '/auth-redirect']
// 属性 path ： 以'/'开始表示绝对路由 ; 否则，代表相对路由
const constantRoutes =[
    {
        path: '/404',
        name: '404',
        component: () => import('@/components/404.vue'),
        meta: { title: '找不到页面', icon: '' },
    },
    {
        path: '/404',
        name: '404',
        component: () => import ('@/components/404.vue'),
        meta: {  title: '找不到页面', icon: '' },
    },
    {
        path: "/i18n",
        name: "i18n",
        component: () => import ('@/components/I18n'),
        meta: { title: '国际化语言', icon: '' },
    },
    {
        path: "/login",
        name: "Login",
        component: () => import ('@/components/Login'),
        meta: { title: '登录', icon: '' },

    }
]
// const dynamicRoutes = []

// const dynamicRoutes =[
//     {
//         path: "/",
//         name: "index",
//         component: () => import ('@/components/Layout'),
//         redirect:'/dashboard',
//         meta: { title: '首页', icon: '' },
//         children: [
//             {
//                 path: "/dashboard",
//                 name: "dashboard",
//                 component: () => import ('@/views/Dashboard'),
//                 meta: {  title: '系统首页', icon: ''},
//             }
//         ]
//     },
//     {
//         path: "/system",
//         name: "system",
//         component: () => import ('@/components/Layout'),
//         // redirect:'/dashboard',
//         meta: { title: '系统设置', icon: '' },
//         children: [
//             {
//                 path: "profile",
//                 name: "profile",
//                 component: () => import ('@/views/system/Profile'),
//                 meta: {  title: '个人设置', icon: ''},
//             },
//             {
//                 path: "user",
//                 name: "sysUser",
//                 component: () => import ('@/views/system/SysUser'),
//                 meta: {  title: '用户管理', icon: ''},
//             },
//             {
//                 path: "role",
//                 name: "sysRole",
//                 component: () => import ('@/views/system/SysRole'),
//                 meta: {  title: '角色管理', icon: ''},
//             },
//             {
//                 path: "resource",
//                 name: "sysResource",
//                 component: () => import ('@/views/system/SysResource'),
//                 meta: {  title: '资源管理', icon: ''},
//             },
//         ]
//     },
//     {
//         path: "/service",
//         name: "service",
//         component: () => import ('@/components/Layout'),
//         // redirect:'/dashboard',
//         meta: { title: '服务管理', icon: '' },
//         children: [
//             {
//                 path: "mysql",
//                 name: "mysql",
//                 component: () => import ('@/views/service/Mysql.vue'),
//                 meta: {  title: 'mysql服务管理', icon: ''},
//             },
//             {
//                 path: "redis",
//                 name: "redis",
//                 component: () => import ('@/views/service/Redis.vue'),
//                 meta: {  title: 'redis服务管理', icon: ''},
//             },
//         ]
//     },
//     {
//         path: "/device",
//         name: "device",
//         component: () => import ('@/components/Layout'),
//         // redirect:'/dashboard',
//         meta: { title: '设备管理', icon: '' },
//         children: [
//             {
//                 path: "laptop",
//                 name: "laptop",
//                 component: () => import ('@/views/device/Laptop.vue'),
//                 meta: {  title: '笔记本管理', icon: ''},
//             },
//             {
//                 path: "desktop",
//                 name: "desktop",
//                 component: () => import ('@/views/device/Desktop.vue'),
//                 meta: {  title: '台式机管理', icon: ''},
//             },
//         ]
//     },
// ]
const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes: constantRoutes
});

export function resetRouter() {
    return createRouter({
        history: createWebHistory(process.env.BASE_URL),
        routes: constantRoutes
    });
}

router.beforeEach(async(to, from, next) => {
    NProgress.start()
    document.title = to.meta.title
    if (getToken()) {
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            const hasRouters = store.getters.routers && store.getters.routers.length > 0
            if (hasRouters) {
                next()
            } else {
                try {
                    //这是有返回值的，返回的是{ user,roles ,menus , routers}
                    // await： 等待后面的异步调用完成，并返回结果
                    // const { user,roles ,menus , routers } =  await store.dispatch('getInfo')
                    const { routers } =  await store.dispatch('getInfo')
                    //vue-cli2 存在这样的一个方法，vue-cli3已经弃用
                    //参数是：路由数组
                    // router.addRoutes(constantRoutes)
                    //是vue-cli3新增的方法，只能添加一个路由对象，所以添加动态路由只能采用遍历添加
                    //参数是 ： 单个路由对象
                    // router.addRoute(constantRoute)
                    // dynamicRoutes.forEach(r => router.addRoute(r))
                    routers.forEach(r =>router.addRoute(r))
                    next({ ...to, replace: true })
                } catch (error) {
                    await store.dispatch('resetToken')
                    ElMessage.error(error || 'Has Error')
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})
export default router;
